﻿using Microsoft.Data.Sqlite;
using SSC.Models;
using SSC.Services;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace SSC.ViewModels
{
    public class UserViewModel : INotifyPropertyChanged
    {
        private readonly UserService _userService;
        private ObservableCollection<UserModel> _users;
        public ObservableCollection<UserModel> Users
        {
            get { return _users; }
            set
            {
                _users = value;
                OnPropertyChanged();
            }
        }
        private UserModel _selectedUser;
        public UserModel SelectedUser
        {
            get => _selectedUser;
            set
            {
                _selectedUser = value;
                OnPropertyChanged(nameof(SelectedUser)); // 如果你继承了 INotifyPropertyChanged
            }
        }


        public UserViewModel()
        {
            _userService = new UserService();
            _users = new ObservableCollection<UserModel>(); // 初始化为一个空集合
            LoadUsers(); // 加载现有的用户
        }

        // 从 UserService 加载所有用户
        private void LoadUsers()
        {
            var users = _userService.GetAllUsers(); // 假设这个方法返回所有用户
            Users = new ObservableCollection<UserModel>(users);
        }

        // 新增用户的方法
        public void AddUser(UserModel newUser)
        {
            // 将新用户添加到 Users 集合中
            _userService.AddUser(newUser); 
            LoadUsers(); 
        }
        //删除用户的方法
        public void DeleteUser(UserModel user)
        {
            if (user == null) return;

            _userService.DeleteUser(user); // 如果你用的是 ID，可以传 ID
            LoadUsers(); 
        }
       

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
